<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay', 'unfold']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('shop.goods.goods.quick Search Fields') })"
        >
        </TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef">
            <template #expand>
                <el-table-column type="expand">
                    <template #default="props">
                        <el-table :data="props.row.sku" class="sku-container">
                            <el-table-column
                                :label="t('shop.goods.goods.spec_name')"
                                prop="spec"
                                align="center"
                                :show-overflow-tooltip="true"
                                width="240"
                            />
                            <el-table-column :label="t('shop.goods.goods.spec_image')" prop="image" width="140" align="center">
                                <template #default="{ row }">
                                    <el-image
                                        :src="fullUrl(row.image)"
                                        style="width: 40px; height: 40px"
                                        fit="cover"
                                        :preview-src-list="[fullUrl(row.image)]"
                                        :preview-teleported="true"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column :label="t('shop.goods.goods.spec_price')" prop="price" width="180" align="center">
                                <template #default="{ row }">
                                    <div class="sku-price">
                                        <el-text class="sku-price-current"> {{ row.price.toFixed(2) }}</el-text>
                                        <el-text class="sku-price-origin"> {{ row.origin_price.toFixed(2) }}</el-text>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column :label="t('shop.goods.goods.sale_num')" prop="sales" width="135" align="center" />
                            <el-table-column :label="t('shop.goods.goods.spec_stock')" prop="stock" width="150" align="center">
                                <template #default="{ row }">
                                    <el-text type="danger" v-if="row.stock <= row.stock_alert">
                                        {{ row.stock }} ({{ t('shop.goods.goods.not_enough_stock') }})
                                    </el-text>
                                    <el-text v-else>{{ row.stock }}</el-text>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
            </template>

            <!-- 图片列表 -->
            <template #image>
                <el-table-column :label="t('shop.goods.goods.images')" width="100" align="center">
                    <template #default="{ row }">
                        <el-image
                            :src="fullUrl(row.images[0])"
                            style="width: 60px; height: 60px"
                            fit="cover"
                            :preview-src-list="row.images.map((item: any) => fullUrl(item))"
                            :preview-teleported="true"
                        />
                    </template>
                </el-table-column>
            </template>
            <!-- 售价 -->
            <template #sale_price>
                <el-table-column :label="t('shop.goods.goods.sale_price')" align="center" min-width="150">
                    <template #default="{ row }"> {{ row.min_price }}~{{ row.max_price }}</template>
                </el-table-column>
            </template>
            <!-- 总销量 -->
            <template #total_sale_num>
                <el-table-column :label="t('shop.goods.goods.total_sale_num')" align="center" min-width="120">
                    <template #default="{ row }">{{ getSales(row) }}</template>
                </el-table-column>
            </template>
            <template #total_stock>
                <el-table-column :label="t('shop.goods.goods.stock')" align="center" min-width="120">
                    <template #default="{ row }">
                        <el-text v-if="row.total_stock <= row.stock_alert" type="danger">
                            {{ row.total_stock }} ({{ t('shop.goods.goods.not_enough_stock') }})
                        </el-text>
                        <el-text v-else>{{ row.total_stock }}</el-text>
                    </template>
                </el-table-column>
            </template>
        </Table>

        <!-- 表单 -->
        <PopupForm />

        <!-- 库存弹窗 -->
        <stockDialog v-if="baTable.table.extend!.showStockDialog" />
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref } from 'vue'
import baTableClass from '/@/utils/baTable'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi } from '/@/api/common'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { fullUrl } from '/@/utils/common'
import { ElMessage } from 'element-plus'
import stockDialog from './stockDialog.vue'
import { getClassify, getParamsTemplate, getSpecTemplate } from '/@/api/backend/shop/goods/goods'
import { showEditStockButton } from './index'

defineOptions({
    name: 'shop/goods/goods',
})

const { t } = useI18n()
const tableRef = ref()
const optButtons: OptButton[] = defaultOptButtons(['weigh-sort', 'edit', 'delete'])

optButtons.push({
    render: 'tipButton',
    // name 是任意的
    name: 'editStock',
    // title 是语言翻译 key
    title: 'shop.goods.goods.edit_stock',
    text: '',
    type: 'warning',
    icon: 'el-icon-Box',
    click(row) {
        baTable.table.extend!.showStockDialog = true
        baTable.table.extend!.rowData = row
    },
    display: (row: TableRow) => {
        return showEditStockButton(row)
    },
})

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/shop.goods.Goods/'),
    {
        pk: 'id',
        column: [
            {
                render: 'slot',
                slotName: 'expand',
                operator: false,
            },
            { type: 'selection', align: 'center', operator: false },
            {
                label: t('shop.goods.goods.id'),
                prop: 'id',
                align: 'center',
                width: 70,
                operator: 'RANGE',
                sortable: 'custom',
            },

            {
                label: t('shop.goods.goods.name'),
                prop: 'name',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                operator: false,
                sortable: false,
                width: 280,
                showOverflowTooltip: true,
            },
            // 搜索用
            {
                label: t('shop.goods.goods.classify_name'),
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                comSearchRender: 'remoteSelect',
                remote: {
                    remoteUrl: '/admin/shop.goods.Classify/index',
                },
                show: false,
            },
            {
                label: t('shop.goods.goods.images'),
                prop: 'images',
                align: 'center',
                render: 'slot',
                slotName: 'image',
                operator: false,
            },
            {
                label: t('shop.goods.goods.classify_name'),
                align: 'center',
                render: 'tags',
                prop: 'classify_name',
                minWidth: 200,
                operator: false,
                className: 'classify-column',
                showOverflowTooltip: true,
            },
            {
                label: t('shop.goods.goods.status'),
                prop: 'status',
                align: 'center',
                operator: 'eq',
                width: 100,
                replaceValue: { '1': t('shop.goods.goods.status 1'), '0': t('shop.goods.goods.status 0') },
                render: 'customSwitch',
                comSearchRender: 'select',
                custom: {
                    activeText: t('shop.goods.goods.status 1'),
                    inactiveText: t('shop.goods.goods.status 0'),
                },
            },
            {
                label: t('shop.goods.goods.sale_price'),
                prop: 'sale_price',
                align: 'center',
                operator: false,
                render: 'slot',
                slotName: 'sale_price',
            },
            {
                label: t('shop.goods.goods.stock'),
                prop: 'total_stock',
                align: 'center',
                operator: 'RANGE',
                sortable: true,
                width: 120,
                render: 'slot',
                slotName: 'total_stock',
            },
            {
                label: t('shop.goods.goods.total_sale_num'),
                prop: 'total_sale_num',
                align: 'center',
                operator: false,
                render: 'slot',
                slotName: 'total_sale_num',
            },
            {
                label: t('shop.goods.goods.sales_real'),
                prop: 'sales_real',
                align: 'center',
                sortable: true,
                operator: 'RANGE',
                width: 130,
            },
            {
                label: t('shop.goods.goods.visit'),
                prop: 'visit',
                align: 'center',
                operator: false,
                sortable: true,
                width: 130,
            },
            {
                label: t('shop.goods.goods.create_time'),
                prop: 'create_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            {
                label: t('shop.goods.goods.update_time'),
                prop: 'update_time',
                align: 'center',
                render: 'datetime',
                operator: false,
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            {
                label: t('Operate'),
                align: 'center',
                width: 180,
                render: 'buttons',
                buttons: optButtons,
                operator: false,
                fixed: 'right',
            },
        ],
        dblClickNotEditColumn: ['undefined'],
    },
    {
        defaultItems: { status: 1, delivery_type: 1, deduct_stock_type: 1 },
    },
    {
        onSubmit({ formEl, operate, items }) {
            if (items.spec_data.skuList.length <= 0) {
                ElMessage.error(t('shop.goodsSpec.The specification SKU data is incomplete'))
                return false
            } else {
                const specList = items.spec_data.specList
                for (let i = 0; i < specList.length; i++) {
                    const item = specList[i]
                    if (item.name == '' || item.value.length <= 0) {
                        ElMessage.error(t('shop.goodsSpec.The specification attributes are incomplete'))
                        return false
                    }
                }
            }

            // 表单验证通过后执行的api请求操作
            let submitCallback = () => {
                baTable.form.submitLoading = true
                baTable.api
                    .postData(operate, items)
                    .then((res) => {
                        baTable.onTableHeaderAction('refresh', {})
                        baTable.form.submitLoading = false
                        baTable.form.operateIds?.shift()
                        if (baTable.form.operateIds!.length > 0) {
                            baTable.toggleForm('Edit', baTable.form.operateIds)
                        } else {
                            baTable.toggleForm()
                        }
                        baTable.runAfter('onSubmit', { res })
                    })
                    .catch(() => {
                        baTable.form.submitLoading = false
                    })
            }

            if (formEl) {
                baTable.form.ref = formEl
                formEl.validate((valid) => {
                    if (valid) {
                        submitCallback()
                    } else {
                        ElMessage.error(t('shop.lang.The formdata is incomplete'))
                    }
                })
            } else {
                submitCallback()
            }
            return false
        },
        toggleForm: ({ operate }: { operate: string; operateIds: string[] }) => {
            if (operate) {
                getClassify().then((res) => {
                    baTable.form.extend!.goodsClassifyData = res.data
                })
                getSpecTemplate().then((res) => {
                    baTable.form.extend!.goodsSpecTemplateData = res.data.list
                })
                getParamsTemplate().then((res) => {
                    baTable.form.extend!.goodsParamsTemplateData = res.data.list
                })
            }
        },
    },
    {}
)

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})

//销量
const getSales = (row: TableRow) => {
    return row.sales_init + row.sales_real
}
</script>

<style scoped lang="scss">
.sku-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    max-width: 50%;
    margin-left: 190px;
}
.sku-price {
    display: flex;
    flex-direction: column;
}
.sku-price-current {
    font-size: 14px;
    color: #f00;
}

.sku-price-origin {
    font-size: 14px;
    color: #999;
    text-decoration: line-through;
}
</style>
